package leet;

import org.junit.Test;

/**
 * @author fance
 * @date 18-5-11 上午5:51
 */
public class BitSum {


    /**
     * 191. 位1的个数
     * @param n
     * @return
     */
    public int hammingWeight(int n) {
//         return Integer.bitCount(n);
        int res = 0;
        while (n > 0) {
            n = n & (n - 1);
            res++;
        }
        return res;
    }

    /**
     * 231. 2的幂
     * @param n
     * @return
     */
    public boolean isPowerOfTwo(int n) {
        if (n == -2147483648 || n == 0) {
            return false;
        }
        return (n & (n - 1)) == 0;
    }


    /**
     * 338. Bit位计数
     * @param num
     * @return
     */
    public int[] countBits(int num) {
        int[] res = new int[num + 1];
        for (int i = 0; i <= num; i++) {
            res[i] = Integer.bitCount(i);
        }
        return res;
    }


    /**
     * 477. 汉明距离总和
     *
     *
     * @param nums
     * @return
     */
    public int totalHammingDistance(int[] nums) {
        int res = 0;
        if (nums == null || nums.length < 2) {
            return res;
        }
        for (int i = 0; i < nums.length - 1; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                res += Integer.bitCount(nums[i] ^ nums[j]);
            }
        }
        return res;
    }


    /**
     * 371. 两整数之和
     * @param a
     * @param b
     * @return
     */
    public int getSum(int a, int b) {
        int sum,carry;
        do {
            sum = a ^ b;
            carry = (a & b) << 1;
            a = sum;
            b = carry;
        } while (b != 0);
        return sum;
    }


    /**
     * 136. 只出现一次的数字
     * @param nums
     * @return
     */
    public int singleNumber(int[] nums) {
        int res = 0;
        for (int i = 0; i < nums.length; i++) {
            res ^= nums[i];
        }
        return res;
    }

    /**
     * 190. 颠倒二进制位  // todo error
     * @param n
     * @return
     */
    public int reverseBits(int n) {
        StringBuilder sb = new StringBuilder(Integer.toBinaryString(n));
        return Integer.parseInt(sb.reverse().append("000000").toString());
    }
    @Test
    public void test() {
        System.out.println(Integer.toBinaryString(43261596));
        System.out.println(reverseBits(43261596));
    }
}
